import { observable, action, toJS } from 'mobx';
import { message, Button, Modal } from 'antd';
import { WeaLocaleProvider } from 'ecCom';
import _ from 'lodash';
const getLabel = WeaLocaleProvider.getLabel;
const formatMultiLang = WeaLocaleProvider.formatMultiLang;
import { getFieldAssign, listDataSetTableFields, saveFieldAssign, deleteFieldAssign } from "../../apis/dataset";
import React from 'react';
import DialogStore from ".";
import ConditionSetStore from './ConditionSetStore';
import ExcelCellSelect from '../../components/dialog/ExcelCellSelect'
import { each } from 'lodash';

export default class FieldAssignDialogStore extends DialogStore {
    @observable conditionSetStore = new ConditionSetStore();//条件参数
    @observable pageid = "";
    @observable name = "";
    @observable dataSet = "";
    @observable type = "";
    @observable dataSetList = [];
    // @observable dataSetMap = {};
    @observable fieldOptions = [];//可编辑列表数据库字段选择
    @observable targetFieldOptions = [];//目标字段数据源条件字段选择
    @observable tableOptions = [];//数据源中所有数据表
    @observable columns = [];
    @observable datas = [];//赋值操作可编辑列表
    @observable conditionInfo = {};
    @observable typeOptions = [{ key: "0", showname: "无条件赋值" }, { key: "1", showname: "满足特定条件赋值" }];
    @observable width = 1000;
    @observable dialogType = 'normal';
    @observable faMenuVisible = false;
    @observable nameError;
    @observable dataSetError;

    constructor() {
        super();
        this.style = {};
        this.buttons = [<Button onClick={this.onSave} type="primary">{getLabel(30986, '保存')}</Button>,
        <Button onClick={this.clean} type="primary">{'清空条件'}</Button>,
        <Button onClick={this.hideDialog} type="primary">{getLabel('31129', '取消')}</Button>]
    }

    @action hideDialog = () => {
        this.hide();
        //按钮点亮
        const edcExcelDesignerStore = this.parent();
        if (edcExcelDesignerStore) {
            edcExcelDesignerStore.readonly = false;
        }
    }

    @action openDialog = () => {
        this.open();
        //按钮置灰
        const edcExcelDesignerStore = this.parent();
        if (edcExcelDesignerStore) {
            edcExcelDesignerStore.readonly = true;
        }
    }

    @action
    onSave = () => {
        if (!this.name) {
            this.nameError.showError();
            return;
        }
        if (!this.dataSet) {
            this.dataSetError.showError();
            return;
        }
        const datasArr = toJS(this.datas);
        //赋值操作编辑列表必填校验
        let isRequiredWarn = false;
        datasArr.forEach(data => {
            const { dbfield, showname } = data;
            if (!dbfield || dbfield == "" || !showname || showname == "") {
                isRequiredWarn = true;
            }
        });
        if (isRequiredWarn) {
            message.warning("请检查赋值操作必填项是否都已填写", 3);
        } else if (this.datas.length == 0) {
            message.warning("请至少设置一条赋值操作", 3);
        } else if (this.type == "1") {
            const conditionSetStore = this.conditionSetStore;
            conditionSetStore.getShowSql();
            const { conditionInfo, editArr, ruleSql, isChange, targetValue, refObj } = conditionSetStore;
            const { conditiontype, conditionsql2 } = conditionInfo;

            if (conditiontype == 1) {
                if (editArr.length > 0) {
                    message.error(getLabel(384753, "存在字段处理编辑状态，请编辑好后再进行保存操作"));
                    return;
                }
                if (isChange == true && targetValue != "") {
                    Modal.confirm({
                        title: getLabel(385010, "当前目标字段的值未添加到条件中，是否继续保存？"),
                        onOk: () => {
                            if (ruleSql == "") {
                                message.error(getLabel(15364, "条件") + getLabel(130807, "不能为空!"));
                                return;
                            }
                            this.doSaveCondition();
                        },
                        onCancel() {
                            return;
                        },
                    });
                } else {
                    if (ruleSql == "") {
                        message.error(getLabel(15364, "条件") + getLabel(130807, "不能为空!"));
                        return;
                    }
                    this.doSaveCondition();
                }
            } else {
                if (_.trim(formatMultiLang(conditionsql2)) == "") {
                    for (let key in refObj) {
                        if (key == "sql_") {
                            const domkeyRef = refObj[key];
                            domkeyRef.showError();
                            return;
                        }
                    }
                } else {
                    this.doSaveCondition();
                }
            }
        } else {
            this.doSaveCondition();
        }
    }

    doSaveCondition() {
        if (this.type == "1") {
            const conditionSetStore = this.conditionSetStore;
            const { conditionInfo, ruleSql, ruleSqlText } = conditionSetStore;
            const { conditiontype, conditionsql2 } = conditionInfo;

            if (conditiontype == 1) {
                this.conditionInfo = {
                    root: conditionSetStore.root,
                    conditionsql: ruleSql,
                    conditiontext: ruleSqlText,
                    conditiontype: "1"
                };
            } else {
                this.conditionInfo = {
                    conditionsql2: conditionsql2,
                    conditiontype: conditiontype
                };
            }
        } else {
            this.conditionInfo = {};
        }
        saveFieldAssign({
            pageid: this.pageid,
            id: this.id,
            name: this.name,
            dsid: this.dataSet,
            type: this.type,
            conditionInfo: JSON.stringify(this.conditionInfo),
            fieldRelations: JSON.stringify(this.datas)
        }).then(() => {
            this.hideDialog();
            message.success('保存成功');
            if (this.reloadPageFieldAssignList) {
                this.reloadPageFieldAssignList();
            }
        })

    }

    @action
    clean = () => {
        if (this.type == "1") {
            Modal.confirm({
                title: getLabel(84545, "确定清空所有条件？"),
                onOk: () => {
                    this.conditionInfo = {
                        root: {},
                        conditionsql: "",
                        conditiontext: "",
                        conditiontype: "1"
                    };
                    this.initConditionSet(this.type);
                    message.success(getLabel(83885, "操作成功!"));
                },
                onCancel() { },
            });
        } else {
            message.warning("当前选中无条件赋值，不需要清空", 3);
        }
    }

    @action deleteFieldAssign = (id) => {
        Modal.confirm({
            content: getLabel('505984', '是否确认删除？'),
            onOk: () => {
                deleteFieldAssign(id).then(() => {
                    // this.hide();
                    message.success(getLabel('505985', '删除成功'));
                    if (this.reloadPageFieldAssignList) {
                        this.reloadPageFieldAssignList();
                    }
                });
            },
            onCancel() { },
        });
    }

    @action newFieldAssign = (pageid, pageName) => {
        if (!pageid) {
            message.error("请先保存EXCEL，再创建字段赋值");
            return;
        }
        const parent = this.parent();
        if (parent && parent.dataSourceList) {
            if (parent.dataSourceList.length > 0) {
                const dataSetList = parent.dataSourceList.map(d => ({ key: d.uuid, showname: d.name }));
                this.dataSetList = dataSetList;
            } else {
                message.error("请先新建数据源，再创建字段赋值");
                return;
            }
        }
        this.pageid = pageid;
        this.pageName = pageName;
        this.title = '新建字段赋值';
        this.id = "";
        this.name = "";
        this.faMenuVisible = false;
        this.openDialog();
        const clientWidth = document.documentElement.clientWidth - 200;
        const clientHeight = document.documentElement.clientHeight - 100;
        this.style.width = clientWidth;
        this.heihgt = clientHeight;
        this.datas = [];
        this.type = "0";
        this.dataSet = "";
        this.conditionInfo = {
            root: {},
            conditionsql: "",
            conditiontext: "",
            conditiontype: "1"
        };
        //columns,conditionSetStore
        this.columns = [];
        // this.targetFieldOptions = [];
        // this.targetValueOptions = [];
        // this.tableOptions = [];
        //初始化
        this.conditionSetStore.initCondition(this.conditionInfo, this.targetFieldOptions, [], this.tableOptions);
    }

    @action openFieldAssign = (pageid, pageName, id) => {
        this.pageid = pageid;
        this.pageName = pageName;
        this.id = id;
        // this.title = getLabel('503306', '数据集合') + ":"
        this.title = '字段赋值' + ":"
        this.faMenuVisible = false;
        this.openDialog();
        const clientWidth = document.documentElement.clientWidth - 200;
        const clientHeight = document.documentElement.clientHeight - 100;
        this.style.width = clientWidth;
        this.style.width = clientWidth;
        this.heihgt = clientHeight;
        getFieldAssign(id).then(this.setFieldAssign);
    }

    @action
    setFieldAssign = (data) => {
        const { name, dsid, fieldRelations, type, conditionInfo } = data;
        if (fieldRelations) {
            const a = JSON.parse(fieldRelations);
            this.datas = a.map(f => ({ ...f, randomkey: this.createRandomKey(8) }));
        }
        this.name = name;
        this.dataSet = dsid;
        if (conditionInfo) {
            this.conditionInfo = JSON.parse(conditionInfo);
        }
        const parent = this.parent();
        if (parent && parent.dataSourceList) {
            const dataSetList = parent.dataSourceList.map(d => ({ key: d.uuid, showname: d.name }));
            // this.tableOptions = [];
            this.init(dsid, type);
            this.dataSetList = dataSetList;
        }
    }

    /**
     * 切换数据源及其初始化赋值
     */
    @action changeDataSet = (ds) => {
        this.dataSet = ds;
        this.datas = [];
        // this.fieldOptions = [];
        // this.targetFieldOptions = [];
        // this.tableOptions = [];
        this.conditionInfo = {
            root: {},
            conditionsql: "",
            conditiontext: "",
            conditiontype: "1"
        };
        this.type = '0';
        this.init(this.dataSet, this.type);
    }


    @action changeName = (name) => {
        this.name = name;
    }

    /**
     * 切换切赋值条件类型及其初始化赋值
     */
    @action changeSelect(value) {
        this.conditionInfo = {
            root: {},
            conditionsql: "",
            conditiontext: "",
            conditiontype: "1"
        };
        this.initConditionSet(value);
    }

    /**
     * 根据type选择初始化数据
     */
    initConditionSet(type) {
        //切换赋值条件类型,能够选择时必定已经选择了数据源
        if (type === '1') {
            //关联表格字段
            const targetValueOptions = this.getTargetValueOptions();
            //初始化条件赋值组件
            this.conditionSetStore.initCondition(this.conditionInfo, this.targetFieldOptions, targetValueOptions, this.tableOptions);
        }
        this.type = type;
    }

    @action init = (dsid, type) => {
        listDataSetTableFields(dsid).then(result => {
            const tablelist = result;
            this.fieldOptions = [];
            this.targetFieldOptions = [];
            this.tableOptions = [];
            if (tablelist && tablelist.length > 0) {
                tablelist.forEach(t => {
                    this.tableOptions.push(t.showname);
                    if (t.children) {
                        this.fieldOptions = [...this.fieldOptions, ...t.children.map(d => ({ key: t.key + '.' + d.key, showname: t.showname + '.' + d.showname }))];
                        this.targetFieldOptions = [...this.targetFieldOptions, ...t.children.map(d => ({ key: '$' + t.showname + '$.' + d.key, showname: t.showname + '.' + d.showname }))];
                    }
                });
                this.getColumns();
            }
            this.initConditionSet(type);
        });
    }

    @action getColumns = () => {
        this.columns = [
            {
                title: '表格字段',
                dataIndex: 'dataIndex1',
                com: [
                    <ExcelCellSelect
                        options={[{ key: 'empty', showname: <span>&nbsp;</span> }, { key: '1', showname: '字段1' }]}
                        onChangeSize={this.onChangeSize}
                    />

                ],
            },
            {
                title: '数据库字段',
                dataIndex: "dbfield",
                width: '50%',
                com: [
                    {
                        viewAttr: 3,
                        type: "SELECT",
                        key: "dbfield",
                        style: {
                            width: "200px"
                        },
                        options: this.fieldOptions.slice(),
                        showSearch: true
                    }
                ]
            }
        ];
    }

    /**
     * 可编辑列表数据变化事件
     */
    @action
    onChange = (datas) => {
        this.datas = datas;
    }

    @action
    onChangeSize = (dialogType, tableCellProps) => {
        this.dialogType = dialogType;
        this.width = dialogType === 'normal' ? 1000 : 520;
        this.parent().tableCellProps = tableCellProps;
    }

    createRandomKey = (length) => {
        return Math.random().toString(36).substr(2, length);
    }

    @action faShowMenu = (visible) => {
        this.faMenuVisible = visible;
    }

    /**
     * 获取表格字段
     */
    getTargetValueOptions = () => {
        let targetValueOptions = [];
        const parent = this.parent();
        if (parent && parent.workbook) {
            const workbook = parent.workbook.toJSON();
            const { sheets } = workbook;
            if (sheets) {
                each(sheets, (sheet, sheetKey) => {
                    const { data, tables } = sheet;
                    if (data) {
                        const { dataTable } = data;
                        if (dataTable) {
                            each(dataTable, (o) => {
                                each(o, (obj) => {
                                    const { bindingPath, style } = obj
                                    if (bindingPath) {
                                        const { cellType } = style;
                                        if (cellType) {
                                            targetValueOptions.push({
                                                key: `$${bindingPath}$`,
                                                showname: `${sheetKey}.主表.${cellType.fieldName}`
                                            });
                                        }
                                    }
                                });
                            });

                        }
                    }

                    if (tables) {
                        tables.forEach(table => {
                            const { bindingPath, columns, name } = table;
                            const nameArr = name.split('detail');
                            if (nameArr && nameArr[1]) {
                                if (columns) {
                                    columns.forEach(column => {
                                        targetValueOptions.push({
                                            key: `$${bindingPath}.${column.dataField}$`,
                                            showname: `${sheetKey}.明细${nameArr[1]}.${column.dataField}`
                                        });

                                    });
                                }
                            }
                        });
                    }
                });
            }
        }
        return targetValueOptions;
    }
}